package com.enjoy.ioc.dao;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 参与spring初始化Bean的过程，可以将目标对象包装成一个代理对象
 * 从而加上自己的逻辑
 */
//@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (beanName.equals("indexDao")){

			return Proxy.newProxyInstance(this.getClass()
							.getClassLoader(), new Class[]{bean.getClass().getInterfaces()[0]},
					new InvocationHandler() {
						@Override
						public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
							System.out.println("代理前");
							return method.invoke(bean,args);
						}
					});
		}else {
			return bean;
		}
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
}
